package com.xymtop.sqlcater.core.sql.sqlexecute.select.entity;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.xymtop.sqlcater.core.sql.sqlparser.toobj.parse.Parser;
import com.xymtop.sqlcater.core.sql.sqlparser.tosql.entity.sql.SqlApp;
import com.xymtop.sqlcater.core.sql.sqlparser.tosql.entity.xmind.SaveType;
import com.xymtop.sqlcater.core.sql.sqlparser.tosql.utils.CaterFileUtil;
import lombok.Data;
import org.xmind.core.CoreException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//查询的app
@Data
public class SelectAppContent {
    //名称

    private String name = "run";


    //保存路径
    private String path="./";

    //查询语句
    private List<SqlSelect> selects = new ArrayList<>();


    //转为json
    private String toJson(){

        String json = "{\n";

        for(SqlSelect sqlSelect : selects){
            sqlSelect.buildSql();
            json+="\"" + sqlSelect.getName()+"\":"+"\""+sqlSelect.getSql()+"\",\n";
        }

        json = json.substring(0,json.length()-2);
        json+="\n}";
        return json;
    }


    public void out() throws IOException, CoreException, NoSuchFieldException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        String json = toJson();
        ObjectMapper objectMapper = new ObjectMapper();
//         json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
         String outPath = path+name+".json";
         CaterFileUtil.write(json,outPath);

         //输出执行树
        //转换
        Parser parser = Parser.Parser(this).parse();

        //需要去输出
        parser.out(path+name+".exec_tree.json");

        SqlApp sqlApp = new SqlApp();
        sqlApp.run(outPath).out(false,new SaveType[]{SaveType.JSONTREE,SaveType.XMINDTREE,SaveType.JSON,SaveType.XMIND,SaveType.EXECTREE});
    }

}
